package com.api.common.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.api.common.Common;
import com.api.common.jwt.JwtConstant;
import com.api.common.jwt.TokenIgnore;
import com.api.component.CacheComponent;
import com.api.component.JwtComponent;
import com.api.component.MD5UtilComponent;
import com.api.component.ResponseComponent;

import lombok.extern.slf4j.Slf4j;

/**
 * jwt 拦截器
 */
@Slf4j
@Component
public class JwtInterceptor implements HandlerInterceptor {
	@Autowired
	private JwtComponent jwtComponent;
	@Autowired
	private ResponseComponent responseComponent;
	@Autowired
	private MD5UtilComponent md5UtilComponent;
	@Autowired
	private CacheComponent cacheComponent;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 忽略带TokenIgnore注解的请求, 不做后续token认证校验
		if (handler instanceof HandlerMethod) {
			// 注解在方法上
			TokenIgnore loginUserAnnotation = ((HandlerMethod) handler).getMethodAnnotation(TokenIgnore.class);
			// 注解在类上
			TokenIgnore classLoginUserAnnotation = ((HandlerMethod) handler).getMethod().getDeclaringClass()
					.getAnnotation(TokenIgnore.class);
			if (ObjectUtils.anyNotNull(classLoginUserAnnotation, loginUserAnnotation)) {
				return true;
			}
		}

		if (HttpMethod.OPTIONS.equals(request.getMethod())) {
			response.setStatus(HttpServletResponse.SC_OK);
			return true;
		}

		final String token = request.getHeader(JwtConstant.AUTH_HEADER_KEY);

		if (StringUtils.isEmpty(token)) {
			// TODO 这里自行抛出异常
			response.setCharacterEncoding(Common.UTF8);
			response.getWriter().append(responseComponent.toErrorJSON("用户未登录, 请先登录"));
			return false;
		}
		JSONObject userinfo = null;
		try {
			userinfo = JSONObject.parseObject(jwtComponent.verifyToken(token));
		} catch (Exception e) {
			log.error("上送token信息:" + token);
			// TODO: handle exception
			response.setCharacterEncoding(Common.UTF8);
			response.getWriter().append(responseComponent.toErrorJSON("用户未登录"));
			return false;
		}
		String key = md5UtilComponent.md5(Common.TOKEN + userinfo.getString("userid") + userinfo.getString("source"))
				.toUpperCase();
		if (!cacheComponent.isExistsKey(key)) {
			String redisToken = cacheComponent.getCacheValue(key);
			if (!redisToken.equals(token)) {
				response.setCharacterEncoding(Common.UTF8);
				response.getWriter().append(responseComponent.toErrorJSON("账号在其他地方登录,请重新登录"));
				return false;
			}
		} else {
			response.setCharacterEncoding(Common.UTF8);
			response.getWriter().append(responseComponent.toErrorJSON("登录信息过期,请重新登录"));
			return false;
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}
}
